package com.example.newstest.news.fragment;


import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.example.newstest.BR;
import com.example.newstest.callback.NewsService;
import com.example.newstest.databinding.FragmentNewsSecondBinding;
import com.example.newstest.news.bean.heardline.HeardLineData;
import com.example.newstest.news.bean.newsentity.NewsItemEntity;
import com.example.newstest.until.BaseApplication;
import com.example.newstest.until.CommentRecyclerAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.example.newstest.R;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.indicator.PtrIndicator;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class NewsSecondFragment extends Fragment implements Callback<List<HeardLineData>>, PtrHandler {
    private FragmentNewsSecondBinding binding;
    private int t;
    private int tid;
    private int isRefresh = -2;
    private CommentRecyclerAdapter<Object> adapter;
    private NewsService service;
    private boolean isLoading = false;
    private String id ;
    public NewsSecondFragment() {
        // Required empty public constructor
    }

    public static NewsSecondFragment newInstance(String title) {
        Map<String, Pair<Integer, Integer>> map = new HashMap<>();
        map.put("硬件", Pair.create(1, 168));
        map.put("软件", Pair.create(2, 169));
        map.put("手机", Pair.create(3, 170));
        map.put("科技", Pair.create(4, 171));
        Bundle args = new Bundle();
        args.putInt("tid",map.get(title).first );
        args.putInt("t",map.get(title).second);
        NewsSecondFragment fragment = new NewsSecondFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return DataBindingUtil.inflate(inflater, R.layout.fragment_news_second, container, false).getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding = DataBindingUtil.getBinding(view);
       aboutRecycler();
        aboutRefresh();
        aboutNextPage();
    }


    private void aboutNextPage() {
        binding.recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                View item = recyclerView.getChildAt(recyclerView.getChildCount() - 1);
                int position = recyclerView.getChildAdapterPosition(item);
                if (!isLoading && position > adapter.getItemCount() - 5) {
                    service.getNewsItemList(tid,id).enqueue(new Callback<List<NewsItemEntity>>() {
                        @Override
                        public void onResponse(Call<List<NewsItemEntity>> call, Response<List<NewsItemEntity>> response) {
                            id = response.body().get(response.body().size()-1).getId()+"";
                            adapter.addAll(response.body());
                        }

                        @Override
                        public void onFailure(Call<List<NewsItemEntity>> call, Throwable t) {

                        }
                    });
                       isLoading = true;
                }
            }
        });
    }
    private void aboutRefresh() {
        binding.ptr.setPtrHandler(this);
        final ImageView imageView = new ImageView(getContext());
        final TextView textView = new TextView(getContext());
        LinearLayout linearLayout = new LinearLayout(getContext());
        linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.addView(textView);
        linearLayout.addView(imageView);
        imageView.setImageResource(R.mipmap.arrow_down);
        textView.setText("开始刷新,请稍后....");
        textView.setGravity(Gravity.CENTER);
        binding.ptr.setHeaderView(linearLayout);
        binding.ptr.addPtrUIHandler(new PtrUIHandler() {
            @Override
            public void onUIReset(PtrFrameLayout frame) {
                ViewCompat.setScaleY(imageView,1);
                ViewCompat.setScaleX(imageView,1);
                ViewCompat.setRotation(imageView,0);
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {

            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                textView.setText("正在刷新,请稍后...");
                ViewCompat.animate(imageView)
                        .rotation(180)
                        .setDuration(500)
                        .start();
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {

            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                float percent = ptrIndicator.getCurrentPercent();
                percent =  Math.min(percent, 1);
                ViewCompat.setScaleX(imageView, percent);
                ViewCompat.setScaleY(imageView, percent);
            }
        });
    }
    private void aboutRecycler() {
        t = getArguments().getInt("t",0);
        tid = getArguments().getInt("tid",0);
        final Map<Class<?>,Pair<Integer,Integer>> map = new HashMap<>();
        map.put(HeardLineData.class,Pair.create(R.layout.news_second_heardline, BR.heardLineData2));
        map.put(NewsItemEntity.class,Pair.create(R.layout.news_item, BR.NewsItem));
        adapter = new CommentRecyclerAdapter(getContext(),new ArrayList(),map);
        binding.recycler.setAdapter(adapter);
        final BaseApplication application = (BaseApplication) getActivity().getApplicationContext();
        service = application.getService();
        service.getSecondHrardLineList(t).enqueue(this);
        service.getNewsItemList(tid,"0").enqueue(new Callback<List<NewsItemEntity>>() {
            @Override
            public void onResponse(Call<List<NewsItemEntity>> call, Response<List<NewsItemEntity>> response) {
                id = response.body().get(response.body().size()-1).getId()+"";
                adapter.addAll(response.body());
                isLoading=false;
            }

            @Override
            public void onFailure(Call<List<NewsItemEntity>> call, Throwable t) {

            }
        });
    }

    @Override
    public void onResponse(Call<List<HeardLineData>> call, Response<List<HeardLineData>> response) {
        if (isRefresh == -1) {
            adapter.clear();
            adapter.add(0, response.body().get(0));
            isRefresh=-2;
            binding.ptr.refreshComplete();
            isLoading=false;
        }else{
            adapter.add(0, response.body().get(0));
            isLoading=false;
        }
    }

    @Override
    public void onFailure(Call<List<HeardLineData>> call, Throwable t) {
             t.getMessage();
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame,content,header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
         isRefresh=-1;
        service.getSecondHrardLineList(t).enqueue(this);
        service.getNewsItemList(tid,"0").enqueue(new Callback<List<NewsItemEntity>>() {
            @Override
            public void onResponse(Call<List<NewsItemEntity>> call, Response<List<NewsItemEntity>> response) {
                adapter.addAll(response.body());
            }

            @Override
            public void onFailure(Call<List<NewsItemEntity>> call, Throwable t) {

            }
        });
    }
}
